﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;
using SmsControl;

namespace TestSMSApp
{
    public partial class Form1 : Form
    {
        SmsControl.SmsControl control;
        //CommSetting control = new CommSetting();

        public Form1()
        {
            InitializeComponent();
            control = new SmsControl.SmsControl();
        }

        delegate void SetTextCallback(Control ctrl, string text);

        private void SetText(Control ctrl, string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (ctrl.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] {ctrl, text });
            }
            else
            {
                ctrl.Text = text;
            }
        }

        private void ReceiveSMS(List<SmsControl.SMS> smslist)
        {
            if (smslist == null) { return; }
            if (smslist.Count == 0) { return; }

            SMS obj = smslist[0];

            //txtReceiveNum.Text = obj.Number;
            //txtReceiveContent.Text = obj.Content;

            string receiveNum = (new StringBuilder(obj.Number)).ToString();
            string receiveContent = (new StringBuilder(obj.Content)).ToString();
            
            //txtReceiveNum.Text = receiveNum;
            //txtReceiveContent.Text = receiveContent;

            SetText(txtReceiveNum, receiveNum);

            SetText(txtReceiveContent, receiveContent);
        }        

        private void btnSend_Click(object sender, EventArgs e)
        {
            control.Send(txtSendNum.Text, txtSendContent.Text);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<string> lstPort = SmsControl.SmsControl.GetListPort().ToList();
            cbbPort.DataSource = lstPort;

            control.NewMessageReceived += ReceiveSMS;
        }

        private void btnSetPort_Click(object sender, EventArgs e)
        {
            control.Initialize(cbbPort.Text);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            control.Disconnect();
            GC.Collect();
            Environment.Exit(0);
            
        }
    }
}